using UnityEngine;
using System.Collections;

public class SpawnFeeder : MonoBehaviour {
	public bool showHelpUI = true;
	public RespawnHandler handler = null;
	public GameObject[] prototypes = new GameObject[]{};
	
	public float frequency 				= 20.0f;
	public float intervalRandomization 	= 10.0f;
	
	public NetworkEntityMgr networkMgr;
	private int idCounter = 0;
	
	private float timer;
	
	protected GameObject getPrototype() {
		return prototypes[Random.Range(0, prototypes.Length)];
	}
	
	void Start() {
		setTimer();
	}
	
	void Update() {
		if (Time.time >= timer) {
			spawnEntity();
			setTimer();
		}
	}
	
	private void setTimer() {
		timer = Time.time + frequency + Random.Range(-intervalRandomization / 2f, intervalRandomization / 2f);
	}
	
	public void spawnEntity() {
//		if (Network.isServer) {
//			//Hack:
//			GameObject newObject = ((GameObject) Network.Instantiate(getPrototype(), Vector3.zero, Quaternion.identity, 0)); 
//			//GameObject newObject = Instantiate(getPrototype(), Vector3.zero, Quaternion.identity) as GameObject;
//			Debug.Log (newObject);
//	
//			if (!handler.spawnObject(newObject)) {
//				Debug.Log("Failed to spawn Entity at any spawn location");
//				Network.Destroy(newObject);
//			}
//		}
//	}
		 if(Network.isServer){
			GameObject newObject = Instantiate(getPrototype(), Vector3.zero, Quaternion.identity) as GameObject;
			
			if (newObject.GetComponent<Entity>() == null) {
				Debug.LogError("Attempting to spawn something that is not an Entity: " + newObject);
			}
			
			if (!handler.spawnObject(newObject)){
				Destroy(newObject);  
				//networkMgr.networkView.RPC("destroyEntity",RPCMode.AllBuffered,newObject.GetComponent<Entity>().entityID); 
			}
			else{
				Debug.Log("Will Spawn"); 
				networkMgr.networkView.RPC("spawnEntity",RPCMode.OthersBuffered,idCounter,newObject.GetComponent<Entity>().entityType,newObject.transform.position,newObject.transform.rotation);
				newObject.GetComponent<Entity>().entityID = idCounter;
				idCounter++; 
			} 
		} 
	}
}
